package com.wd.live.ui.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import com.amap.api.location.AMapLocation
import com.bumptech.glide.Glide
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread
import com.wd.live.R
import com.wd.live.databinding.FragmentPrepareBinding
import com.wd.live.tool.LocalData
import com.wd.live.tool.getLoginInfo
import com.wd.live.tool.longToast
import com.wd.live.tool.lunchActivity
import com.wd.live.ui.activity.OpenLiveActivity
import com.wd.live.ui.dailog.UserHeaderDialog
import com.wd.live.ui.dailog.SelectLiveTypeDialog
import com.wd.live.viewmodel.MainViewModel
import java.io.File

/**
 * 准备开播
 * @author nick.WU
 * @since 2013-08-25
 * A simple [Fragment] subclass.
 * Use the [PrepareFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class PrepareFragment : Fragment(R.layout.fragment_prepare) {
    private var locationInfo: AMapLocation? = null
    private var currentType: LocalData.TypeInfo? = null

    //直播背景
    private var liveBg: String? = null
    private lateinit var photoDialog: UserHeaderDialog

    private val viewModel: MainViewModel by viewModels(ownerProducer = { requireActivity() })
    private var _binding: FragmentPrepareBinding? = null
    private val binding get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        _binding = FragmentPrepareBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //通过viewModel作用域，共享消息，接收地理位置消息
        viewModel.location.observe(viewLifecycleOwner) {
            locationInfo = it
            binding.location.text = it.address
        }
        val loginInfo = context?.getLoginInfo()
        loginInfo?.let {
            Glide.with(binding.coverImg).load(it.headPic).into(binding.coverImg)
        }
        photoDialog =
            UserHeaderDialog(context, requireActivity())
        photoDialog.setOnSelectListener(object :
            UserHeaderDialog.onItemClickListener {
            override fun onFile(mPhoto: List<String?>) {
                runOnUiThread {
                    liveBg = mPhoto[0]?.apply {
                        Glide.with(binding.coverImg).load(File(this)).into(binding.coverImg)
                    }

                }
            }
        })
        binding.coverImg.setOnClickListener {
            context?.let {
                XXPermissions.with(it)
                    .permission(
                        Permission.READ_MEDIA_IMAGES,
                        Permission.READ_MEDIA_VIDEO,
                        Permission.CAMERA
                    )
                    .request { permissions, allGranted ->
                        if (allGranted) {
                            //打开图像选择
                            photoDialog.show()
                        } else {
                            longToast("没有获取全部权限")
                        }
                    }
            }
        }
        binding.liveType.setOnClickListener {
            SelectLiveTypeDialog(requireActivity(), currentType) {
                this@PrepareFragment.currentType = it
            }.apply {
                setOnDismissListener {
                    currentType?.name?.let {
                        binding.liveType.text = it
                    }
                }
            }.show()
        }

        binding.openLive.setOnClickListener {
            if (liveBg == null) {
                longToast("请选择背景图片")
                return@setOnClickListener
            }
            if (currentType?.id == null) {
                longToast("请选选择直播类型")
                return@setOnClickListener

            }
            if (binding.liveName.text.isNullOrEmpty()) {
                longToast("请输入直播间名称")
                return@setOnClickListener

            }
            lunchActivity<OpenLiveActivity>(
                "live_message",
                LocalData.LiveMessage(
                    (liveBg ?: loginInfo?.headPic)!!,
                    currentType?.id!!,
                    binding.liveName.text.toString(),
                    lat = locationInfo?.latitude,
                    lng = locationInfo?.longitude
                )
            )
        }
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @return A new instance of fragment PrepareFragment.
         */
        @JvmStatic
        fun newInstance() =
            PrepareFragment().apply {

            }
    }
}